package com.hudson.broker.config;

import com.hudson.broker.utils.InetAddressUtil;
import com.hudson.core.util.PropertiesUtil;
import com.hudson.core.util.StringUtil;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Properties;

public class BrokerConfig {
    public static boolean USE_EXTERNAL_CONFIG = false; // 新增标记
    public static String CONFIG_FILE_NAME = "Config.properties"; // 新增标记
    //    public static String NAME_SRV_ADDRESS;
    public static int NAME_SRV_PORT;
    // 发送的宿主机地址,让生产消费者访问
    public static String BROKER_ADDRESS;
    // 监听地址,需为0.0.0.0
    public static String BROKER_BIND_ADDRESS;
    public static int BROKER_PORT;
    public static String BROKER_NAME;
    public static boolean FLUSH_METHOD;
    public static int serializableMethod;
    public static List<InetSocketAddress> NAME_SRV_ADDRESS = new ArrayList<>();

    static {
        Properties prop;
        if (USE_EXTERNAL_CONFIG) {
            prop = PropertiesUtil.getProperties(CONFIG_FILE_NAME, true);
        } else {
            prop = PropertiesUtil.getProperties(CONFIG_FILE_NAME);
        }
        String nameSrvAddress = String.valueOf(prop.getProperty("NameSrvAddress", "127.0.0.1:12222"));
        if (StringUtil.noEmpty(nameSrvAddress)) {
            String[] addressArr = nameSrvAddress.split(",");
            for (String address : addressArr) {
                String[] split = address.split(":");
                NAME_SRV_ADDRESS.add(new InetSocketAddress(split[0], Integer.parseInt(split[1])));
            }
        }
//        NAME_SRV_ADDRESS = String.valueOf(prop.getProperty("NameSrvAddress", "127.0.0.1:12222"));
//        NAME_SRV_PORT = Integer.parseInt(prop.getProperty("NameSrvPort", "8080"));

        BROKER_ADDRESS = String.valueOf(prop.getProperty("BrokerAddress", Optional.ofNullable(InetAddressUtil.get()).map(InetAddress::getHostAddress).orElse("127.0.0.1")));
        BROKER_BIND_ADDRESS = String.valueOf(prop.getProperty("BrokerBindAddress", Optional.ofNullable(InetAddressUtil.get()).map(InetAddress::getHostAddress).orElse("127.0.0.1")));
        BROKER_PORT = Integer.parseInt(prop.getProperty("BrokerPort", "8080"));
        BROKER_NAME = String.valueOf(prop.getProperty("BrokerName"));

        FLUSH_METHOD = Boolean.valueOf(prop.getProperty("async", "false"));
        serializableMethod = Integer.parseInt(prop.getProperty("serializableMethod", String.valueOf(0)));
    }
}
